package com.jhx.video.draftbox

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.support.constraint.ConstraintLayout
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.jhx.common.framework.QuickBaseFragment
import com.jhx.common.model.Event
import com.jhx.common.model.Video
import com.jhx.common.utils.ImageLoader
import com.jhx.video.R
import com.jhx.video.publish.VideoPublishActivity
import com.jhx.video.publish.VideoPublishFragment
import com.jhx.video.shortvideo.editor.VideoPreprocessActivity
import com.jhx.video.utils.DensityUtil
import com.jhx.video.utils.TCConstants
import kotlinx.android.synthetic.main.fragment_draftbox.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.io.File
import java.text.SimpleDateFormat

/**
 * 草稿箱
 * @author Jack 2018-03-07 17:31
 */
class DraftBoxFragment :  QuickBaseFragment(), Contract.DraftBoxView {
    private var mAdapter: BaseQuickAdapter<Video, BaseViewHolder>? = null
    private var mPresenter: DraftBoxPresenterImpl? = null
    private var mVideoList: ArrayList<Video>? = ArrayList()
    private var mPosition: Int? = -1
    private var mIsFirst: Boolean = true
    private var mIsEdit: Boolean = false
    private var mEmptyView: View? = null

    override fun bindView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.fragment_draftbox, container, false)
    }

    @SuppressLint("MissingSuperCall")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        setTitle("草稿箱")
        setMenuText("管理")
        initView()
        mPresenter = DraftBoxPresenterImpl()
        mPresenter?.setView(this)
        mPresenter?.getCacheVideo()
        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    override fun showToolbar(): Boolean {
        return true
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mEmptyView = view.findViewById(R.id.empty_layout)
    }

    fun initView() {
        mAdapter = object: BaseQuickAdapter<Video, BaseViewHolder>(R.layout.item_video_layout, mVideoList) {
            override fun convert(holder: BaseViewHolder?, video: Video?) {
                val dateformat = SimpleDateFormat("yyyy-MM-dd hh:mm")
                val delText = holder?.getView<TextView>(R.id.txt_del)
                val editView = holder?.getView<ConstraintLayout>(R.id.view_edit)
                val publishText = holder?.getView<TextView>(R.id.txt_release)
                val delImage = holder?.getView<ImageView>(R.id.img_delete)
                holder?.setText(R.id.txt_time, dateformat.format(video?.create_time))
                if(video?.cover_url?.contains("http://") == true || video?.cover_url?.contains("https://") == true) {
                    ImageLoader.get().loadImageByUrl(context = context,
                            url = "${video.cover_url}",
                            imageView = holder?.getView(R.id.videoview))
                } else {
                    val file = File("${video?.cover_url}")
                    Glide.with(activity).load(file).into(holder?.getView(R.id.videoview))
                }
                val layoutParams = editView?.layoutParams
                layoutParams?.width = resources.displayMetrics.widthPixels
                editView?.layoutParams = layoutParams
                if(mIsEdit) {
                    delImage?.visibility = View.VISIBLE
                    publishText?.visibility = View.GONE
                    if(holder?.adapterPosition == mPosition) {
                        hideDelBtn(editView, delText, -DensityUtil.dip2px(activity, 60f).toFloat())
                    }
                } else {
                    if(delText?.visibility == View.VISIBLE) {
                        hideDelBtn(editView, delText, -DensityUtil.dip2px(activity, 60f).toFloat())
                    }
                    delImage?.visibility = View.GONE
                    publishText?.visibility = View.VISIBLE
                }
                delImage?.setOnClickListener {
                    delImage.visibility = View.GONE
                    delText?.visibility = View.VISIBLE
                    showDelBtn(editView, delText, -DensityUtil.dip2px(activity, 60f).toFloat())
                }
                delText?.setOnClickListener {
                    if(video != null) {
                        mPresenter?.delVideo(video) {
                            mPosition = holder.adapterPosition
                            mAdapter?.data?.remove(video)
                            mAdapter?.notifyDataSetChanged()
                            val event = Event()
                            event.code = Video.CODE_ADD
                            EventBus.getDefault().post(event)
                        }
                    }
                }
                holder?.getView<FrameLayout>(R.id.fl_item)?.setOnClickListener {
                    val intent = Intent(activity, VideoPreprocessActivity::class.java)
                    intent.putExtra(TCConstants.VIDEO_EDITER_PATH, "${video?.video_url}")
                    intent.putExtra(TCConstants.VIDEO_RECORD_COVERPATH, "${video?.cover_url}")
                    intent.putExtra(TCConstants.VIDEO_RECORD_DESCMSG, "${video?.context}")
                    intent.putExtra(TCConstants.VIDEO_RECORD_ID, "${video?.id}")
                    intent.putExtra(TCConstants.VIDEO_RECORD_DURATION, "${video?.countTime}")
                    intent.putExtra(VideoPublishFragment.KEY_FROM, VideoPublishFragment.FROM_DRAFT)
                    startActivity(intent)
                }
                publishText?.setOnClickListener {
                    val intent = Intent(activity, VideoPublishActivity::class.java)
                    intent.putExtra(VideoPublishFragment.VIDEO_DATA, video)
                    intent.putExtra(VideoPublishFragment.KEY_FROM, VideoPublishFragment.FROM_DRAFT)
                    startActivity(intent)
                }
            }

        }
        recycler_view.itemAnimator = DefaultItemAnimator()
        recycler_view.layoutManager = LinearLayoutManager(activity)
        recycler_view.addItemDecoration(DividerItemDecoration(context, LinearLayoutManager.VERTICAL))
        recycler_view.adapter = mAdapter
    }


    /**
     * 显示隐藏删除按钮
     */
    fun showDelBtn(view1: View?, view2: View?, toX: Float?) {
        if(view1 != null && view2 != null && toX != null) {
            val animation = ObjectAnimator.ofFloat(view1, "X", 0f, toX)
            val delAnimator = ObjectAnimator.ofFloat(view2, "alpha", 0f, 1f)
            val animatorSet = AnimatorSet()
            animatorSet.play(animation).with(delAnimator)
            animatorSet.duration = 500
            animatorSet.start()
        }
    }

    /**
     * 隐藏删除按钮
     */
    fun hideDelBtn(view1: View?, view2: View?, fromX: Float?) {
        if(view1 != null && view2 != null && fromX != null) {
            val animation = ObjectAnimator.ofFloat(view1, "X", fromX, 0f)
            val delAnimator = ObjectAnimator.ofFloat(view2, "alpha", 1f, 0f)
            val animatorSet = AnimatorSet()
            animatorSet.play(animation).with(delAnimator)
            animatorSet.duration = 500
            animatorSet.start()
            Handler().postDelayed({
                view2.visibility = View.GONE
            }, 500)
        }
    }

    override fun showLoading() {
        showLoadingDialog()
    }

    override fun hideLoading() {
        hideLoadingDialog()
    }

    override fun getVideoListSuccess(list: List<Video>?) {
        if(list?.isNotEmpty() == true) {
            mEmptyView?.visibility = View.GONE
            recycler_view.visibility = View.VISIBLE
            mAdapter?.data?.clear()
            mAdapter?.setNewData(list)
        } else {
            mEmptyView?.visibility = View.VISIBLE
            recycler_view.visibility = View.GONE
        }
    }

    override fun getContext(): Activity? {
        return activity
    }

    override fun onMenuClick(view: View?) {
        super.onMenuClick(view)
        mIsEdit = !mIsEdit
        if(mIsEdit) {
            setMenuText("完成")
        } else {
            setMenuText("管理")
            mIsFirst = false
        }
        mAdapter?.notifyDataSetChanged()
    }

    override fun onDestroyView() {
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroyView()
    }

    @Subscribe
    fun onEvent(event: Event?) {
        if(event != null) {
            when(event.code) {
                Video.CODE_UPDATE -> {
                    mAdapter?.data?.clear()
                    mPresenter?.getCacheVideo()
                }
            }
        }
    }
}